package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.base.model.ErrR;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class TeachplanServiceImpl implements TeachplanService {
    @Autowired
    private TeachplanMapper teachplanMapper;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public List<TeachplanDto> findTeachplanTree(long courseId) {
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId);
        queryWrapper.orderByAsc(Teachplan::getOrderby);
        List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
        List<TeachplanDto> nodeList = new ArrayList<>();
        if (teachplans.size() == 0) {
            return nodeList;
        }
        for (Teachplan courseCategory : teachplans) {
            TeachplanMedia teachplanMediaNew = null;
            Long teachplanId = courseCategory.getId();
            LambdaQueryWrapper<TeachplanMedia> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(TeachplanMedia::getTeachplanId, teachplanId);
            List<TeachplanMedia> teachplanMedia = teachplanMediaMapper.selectList(queryWrapper1);
            if (teachplanMedia.size() > 0) {
                teachplanMediaNew = teachplanMedia.get(0);
            }
            nodeList.add(new TeachplanDto(
                    courseCategory.getId(),
                    courseCategory.getPname(),
                    courseCategory.getParentid(),
                    courseCategory.getGrade(),
                    courseCategory.getMediaType(),
                    courseCategory.getStartTime(),
                    courseCategory.getEndTime(),
                    courseCategory.getDescription(),
                    courseCategory.getTimelength(),
                    courseCategory.getOrderby(),
                    courseCategory.getCourseId(),
                    courseCategory.getCoursePubId(),
                    courseCategory.getStatus(),
                    courseCategory.getIsPreview(),
                    courseCategory.getCreateDate(),
                    courseCategory.getChangeDate(),
                    teachplanMediaNew));
        }
        List<TeachplanDto> hierarchicalNodes = TeachplanDto.buildHierarchy(nodeList);
        deleteNullChildren(hierarchicalNodes);
        return hierarchicalNodes;
    }


    /**
     * 去除[]，让它变为null
     *
     * @param hierarchicalNodes
     */
    private void deleteNullChildren(List<TeachplanDto> hierarchicalNodes) {
        for (TeachplanDto hierarchicalNode : hierarchicalNodes) {
            if (hierarchicalNode.getTeachPlanTreeNodes().size() == 0) {
                hierarchicalNode.setTeachPlanTreeNodes(null);
            } else {
                deleteNullChildren(hierarchicalNode.getTeachPlanTreeNodes());
            }
        }
    }

    @Override
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {

        Long id = teachplanDto.getId();
        if (id != null) {//id如果不为空则表示修改，因为只有id存在的情况下才能修改，id不存在表示创建
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(teachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);
        } else {
            int count = getTeachplanCount(teachplanDto.getCourseId(), teachplanDto.getParentid());
            Teachplan teachplan = new Teachplan();
            teachplan.setOrderby(count + 1);
            BeanUtils.copyProperties(teachplanDto, teachplan);
            teachplanMapper.insert(teachplan);
        }
    }


    private int getTeachplanCount(Long courseId, Long parentid) {
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentid);
        Integer integer = teachplanMapper.selectCount(queryWrapper);
        return integer;
    }

    @Override
    @Transactional
    public ErrR deleteTeachplan(Long teachplanId) {
//        1、删除大章节，大章节下有小章节时不允许删除。
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan == null) {
            throw new XueChengPlusException("无此课程计划");
        }
        Integer grade = teachplan.getGrade();
        if (grade == 1) {//如果是1就是大章节
            //再判断是否有没有小章节
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid, teachplanId);
            Integer integer = teachplanMapper.selectCount(queryWrapper);
            if (integer != 0) {
                return new ErrR("120409", "课程计划信息还有子级信息，无法操作");
            } else {
                teachplanMapper.deleteById(teachplanId);
            }
        } else {//如果是其他就是小章节，可以直接删，顺带把teachplan_media表关联的信息也删除
            teachplanMapper.deleteById(teachplanId);
            LambdaQueryWrapper<TeachplanMedia> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TeachplanMedia::getTeachplanId, teachplanId);
            teachplanMediaMapper.delete(queryWrapper);
        }
        return null;
    }

    @Override
    public void moveTeachplan(String move, Long teachplanId) {
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getParentid,teachplan.getParentid());
        Teachplan teachplan1=new Teachplan();
        if (move.equals("movedown")) {//向下移动
            //找到跟它同一个父母的
            queryWrapper.eq(Teachplan::getOrderby,teachplan.getOrderby()+1);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            if (teachplans.size()>0){
                teachplan1=teachplans.get(0);
                teachplan1.setOrderby(teachplan1.getOrderby()-1);
                teachplanMapper.updateById(teachplan1);
                teachplan.setOrderby(teachplan.getOrderby()+1);
                teachplanMapper.updateById(teachplan);
            }
        } else {//向上移动
            queryWrapper.eq(Teachplan::getOrderby,teachplan.getOrderby()-1);
            List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
            if (teachplans.size()>0){
                teachplan1=teachplans.get(0);
                teachplan1.setOrderby(teachplan1.getOrderby()+1);
                teachplanMapper.updateById(teachplan1);
                teachplan.setOrderby(teachplan.getOrderby()-1);
                teachplanMapper.updateById(teachplan);
            }
        }
    }

    @Override
    @Transactional
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan==null){
            XueChengPlusException.cast("改课程计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if (grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }

        //删除之前绑定的媒资
        LambdaQueryWrapper<TeachplanMedia> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId,teachplanId);
        teachplanMediaMapper.delete(queryWrapper);

        Long courseId = teachplan.getCourseId();
        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }

    @Override
    public void deleteAssociationMedia(Long teachPlanId, String mediaId) {
        LambdaQueryWrapper<TeachplanMedia> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(TeachplanMedia::getTeachplanId,teachPlanId).eq(TeachplanMedia::getMediaId,mediaId);
        teachplanMediaMapper.delete(queryWrapper);
    }


}
